import { nameDescVerify } from '~/server/validation';
import { AdminPermissionModel } from '~/server/models/admin_permission.model';

/**
 * @api {put} /admin/permission/create 创建后台管理员权限
 * @apiName 创建后台管理员权限
 * @apiGroup 后台管理员权限
 * @apiDescription 创建后台管理员权限
 *
 * @apiPermission admin
 *
 * @apiSampleRequest /admin/permission/create
 *
 * @apiHeader {String} Authorization 用户 Token
 *
 * @apiBody {String} name 权限名称
 * @apiBody {String} description 权限描述
 *
 * @apiSuccess {Number} code 响应状态码
 * @apiSuccess {String} message 响应消息
 * @apiSuccessExample {json} Success-Response:
 * HTTP/1.1 200 OK
 * {
 *   code: 1,
 *   message: '创建成功',
 * }
 */
export default defineEventHandler(async (event) => {
	const checkPermission = checkAdminUserPermission(event, 'admin');
	if (!checkPermission) {
		return {
			code: 0,
			message: '无权访问',
		};
	}

	try {
		const { name, description } = await readBody(event);

		// 参数校验
		const validation: string | undefined = nameDescVerify.validate({
			name,
			description,
		}).error?.message;
		if (validation && validation !== void 0) {
			return {
				code: 0,
				message: validation,
			};
		}

		// 查询是否存在相同名称的权限
		const findResult = await AdminPermissionModel.findOne({ name });
		if (findResult !== null) {
			return {
				code: 0,
				message: '权限名称已存在',
			};
		}

		// 创建权限
		await AdminPermissionModel.create({ name, description });
		return {
			code: 1,
			message: '创建成功',
		};
	} catch (err: any) {
		error(err);
		return {
			code: 0,
			message: err.message,
		};
	}
});
